﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BastInfos.Helpers;
using BastInfos.Models.Article;
using DataAccess;
using DataAccess.Helpers;

namespace BastInfos.Controllers
{
	public class ArticleController : ControllerBase
	{
		[HandleError(ExceptionType = typeof(InvalidOperationException), View = "404")]
		public ActionResult Detail(string title, int id)
		{
			return View(new ArticleModel(DataRepository.Get<Article>()
				.First(a => a.id_Article == id && (a.Status == (byte)StatusType.Visible /*|| UserMembership.IsAuthenticated*/))));
		}

		[HttpPost]
		[HandleError(ExceptionType = typeof(InvalidOperationException), View = "404")]
		public ActionResult Detail(string title, int id, ArticleModel model, Comment comment)
		{
			if (ModelState.IsValid)
			{
				comment.CreationDate = DateTime.Now;
				comment.id_Item = id;
				comment.Validation = (byte)ValidationType.Attente;
				comment.CommentType = (byte)CommentType.Article;

				DataRepository.Context.Comments.InsertOnSubmit(comment);
				DataRepository.Context.SubmitChanges();

				ViewBag.ShowConfirm = true;

				JavaScriptHelper.Instance.WriteScript("$('#spnMessage').fadeIn(500).delay(5000).fadeOut(2500);");
			}
			return View(new ArticleModel(DataRepository.Get<Article>()
				.First(a => a.id_Article == id && (a.Status == (byte)StatusType.Visible /*|| UserMembership.IsAuthenticated*/))));
		}

		public ActionResult List()
		{
			int total = DataRepository.Get<Article>().Count(a => a.Status == (byte)StatusType.Visible);
			int page = GetPage(total);

			IEnumerable<Article> articles = DataRepository.Get<Article>()
				.Where(a => a.Status == (byte)StatusType.Visible)
				.OrderByDescending(a => a.CreationDate)
				.Skip((page - 1) * PAGE_SIZE)
				.Take(PAGE_SIZE);

			return View(new ArticleListModel { CurrentPage = page, PageSize = PAGE_SIZE, TotalItems = total, Articles = articles });
		}

		[HandleError(ExceptionType = typeof(InvalidOperationException), View = "404")]
		public ActionResult Category(string description, int id)
		{
			Category category = DataRepository.Get<Category>().First(c => c.Description == description && c.id_Category == id);
			int total = DataRepository.Get<Article>().Count(a => a.Status == (byte)StatusType.Visible && a.id_Category == category.id_Category);
			int page = GetPage(total);

			IEnumerable<Article> articles = DataRepository.Get<Article>()
				.Where(a => a.Status == (byte)StatusType.Visible && a.id_Category == category.id_Category)
				.OrderByDescending(a => a.CreationDate)
				.Skip((page - 1) * PAGE_SIZE)
				.Take(PAGE_SIZE);

			return View("List", new ArticleListModel { CurrentPage = page, PageSize = PAGE_SIZE, TotalItems = total, Articles = articles, Category = category });
		}
	}
}